package com.innovation.wjrpc.communication;

import com.innovation.wjrpc.transport.Handle;
import com.innovation.wjrpc.transport.RequestHandler;
import com.innovation.wjrpc.transport.TransportServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author innoyiya
 * @date 2021/9/8 17:53
 */
public class NettyTransportServer implements TransportServer {

    private ChannelInboundHandlerAdapter requestHandler;
    private int port = 8080;
    private ChannelFuture channelFuture;
    private EventLoopGroup eventLoopGroup;

    @Override
    public void init(int port, Handle handler) {
        this.port = port;
        this.requestHandler = (ChannelInboundHandlerAdapter) handler;
        this.eventLoopGroup = new NioEventLoopGroup();
    }

    @Override
    public void start() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(eventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(requestHandler);
                    }
                });
        try {
            channelFuture = serverBootstrap.bind().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            try {
                eventLoopGroup.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
